package com.dews.warn.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dews.common.bean.sys.SysRoleVo;
import com.dews.common.core.domain.model.LoginUser;
import com.dews.common.utils.SecurityUtils;
import com.dews.system.domain.SysUser;
import com.dews.system.mapper.SysUserMapper;
import com.dews.warn.convert.NotificationMessageConvert;
import com.dews.warn.domain.dto.NotificationMessageQueryDTO;
import com.dews.warn.domain.entity.NotificationMessage;
import com.dews.warn.domain.vo.NotificationMessageVo;
import com.dews.warn.mapper.NotificationMessageMapper;
import com.dews.warn.service.INotificationMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 消息通知Service业务层处理
 *
 * @author qingfeng
 * @date 2025-02-05
 */
@Service
public class NotificationMessageServiceImpl extends ServiceImpl<NotificationMessageMapper, NotificationMessage> implements INotificationMessageService {

    private NotificationMessageMapper notificationMessageMapper;
    private SysUserMapper sysUserMapper;

    @Autowired
    public NotificationMessageServiceImpl(NotificationMessageMapper notificationMessageMapper,
                                          SysUserMapper sysUserMapper) {
        this.notificationMessageMapper = notificationMessageMapper;
        this.sysUserMapper = sysUserMapper;
    }

    /**
     * 查询消息通知列表
     *
     * @param notificationMessageQueryDTO
     * @return 消息通知
     */
    @Override
    public List<NotificationMessageVo> selectNotificationMessageList(NotificationMessageQueryDTO notificationMessageQueryDTO) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<SysRoleVo> collect = loginUser.getUser().getRoles().stream()
                .filter(role -> "student".equals(role.getRoleKey()))
                .collect(Collectors.toSet());
        List<NotificationMessage> notificationMessageList = baseMapper.selectList(
                Wrappers.lambdaQuery(NotificationMessage.class)
                        .eq(StrUtil.isNotBlank(notificationMessageQueryDTO.getMessageType()), NotificationMessage::getMessageType, notificationMessageQueryDTO.getMessageType())
                        .like(StrUtil.isNotBlank(notificationMessageQueryDTO.getMessageTitle()), NotificationMessage::getMessageTitle, notificationMessageQueryDTO.getMessageTitle())
                        .eq(StrUtil.isNotBlank(notificationMessageQueryDTO.getIsSee()), NotificationMessage::getIsSee, notificationMessageQueryDTO.getIsSee())
                        .eq(CollUtil.isNotEmpty(collect), NotificationMessage::getReceiveUserId, loginUser.getUserId())
        );
        if (CollUtil.isEmpty(notificationMessageList)) {
            return Collections.emptyList();
        }
        Set<Long> userIdSet = notificationMessageList.stream()
                .flatMap(nm -> Stream.of(nm.getSendUserId(), nm.getReceiveUserId()))
                .filter(userId -> userId != -1)
                .collect(Collectors.toSet());
        Map<Long, SysUser> sysUserMap = sysUserMapper.selectBatchIds(userIdSet)
                .stream()
                .collect(Collectors.toMap(
                        SysUser::getUserId,
                        Function.identity()
                ));

        // 如果是学生用户，直接更新消息的状态
        if (CollUtil.isNotEmpty(collect)) {
            notificationMessageMapper.update(
                    null,
                    Wrappers.lambdaUpdate(NotificationMessage.class)
                            .set(NotificationMessage::getIsSee, "Y")
                            .in(NotificationMessage::getId, notificationMessageList.stream().map(NotificationMessage::getId).collect(Collectors.toList()))
            );
        }

        // 封装数据
        return notificationMessageList.stream()
                .map(n -> {
                    NotificationMessageVo notificationMessageVo = NotificationMessageConvert.INSTANCE.convert(n);
                    notificationMessageVo.setSendUserName(n.getSendUserId() == -1 ? "系统默认" : sysUserMap.get(n.getSendUserId()).getNickName());
                    notificationMessageVo.setReceiveUserName(sysUserMap.get(n.getReceiveUserId()).getNickName());
                    return notificationMessageVo;
                })
                .collect(Collectors.toList());
    }

    /**
     * 查询消息通知
     *
     * @param id 消息通知主键
     * @return 消息通知
     */
    @Override
    public NotificationMessageVo selectNotificationMessageById(Integer id) {
        NotificationMessage notificationMessage = notificationMessageMapper.selectById(id);
        if (ObjectUtil.isNotNull(notificationMessage)) {
            NotificationMessageVo notificationMessageVo = NotificationMessageConvert.INSTANCE.convert(notificationMessage);
            SysUser sysUser;
            if (notificationMessage.getSendUserId() != -1) {
                sysUser = sysUserMapper.selectById(notificationMessage.getSendUserId());
                notificationMessageVo.setSendUserName(sysUser.getNickName());
            }
            sysUser = sysUserMapper.selectById(notificationMessage.getReceiveUserId());
            notificationMessageVo.setReceiveUserName(sysUser.getNickName());
            return notificationMessageVo;
        }
        return null;
    }

    /**
     * 批量删除消息通知
     *
     * @param ids 需要删除的消息通知主键
     * @return 结果
     */
    @Override
    public int deleteNotificationMessageByIds(List<Integer> ids) {
        return notificationMessageMapper.deleteBatchIds(ids);
    }

}
